<template>
  <!-- 搜索条件 -->
  <el-row style="margin-bottom: 5px">
    <el-col :span="22">
      <p class="pinformation">搜索条件</p>
    </el-col>
  </el-row>
  <el-form :model="queryParams" label-width="80px" ref="rightJcxmTable">
    <el-row>
      <el-col :span="5">
        <el-form-item label="检测类型：">
          <el-select
            v-model="queryParams.jclbId"
            style="width: 100%"
            filterable
            @change="handleQuery()"
          >
            <el-option
              v-for="item in props.jclbList"
              :key="item.jclbId"
              :label="item.jclbName !== '' ? item.jclbName : item.jclbGroupName"
              :value="item.jclbId"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="检测项目：" prop="jcxmName">
          <el-input
            clearable
            v-model="queryParams.jcxmName"
            maxlength="100"
            @keyup.enter="handleQuery()"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <el-col :span="5">
        <el-form-item label="检测方法：" prop="methodCode">
          <el-input
            clearable
            v-model="queryParams.methodCode"
            maxlength="100"
            @keyup.enter="handleQuery()"
          />
        </el-form-item>
      </el-col>
      <el-col :span="5">
        <el-form-item label-width="20px" prop="isLike">
          <el-radio v-model="queryParams.isLike" label="0">模糊搜索</el-radio>
          <el-radio v-model="queryParams.isLike" label="1">精准搜索</el-radio>
        </el-form-item>
      </el-col>
      <el-col :span="3">
        <el-form-item label-width="10px">
          <el-row :gutter="5">
            <el-col :span="12">
              <el-button type="success" @click="handleQuery()">搜索</el-button>
            </el-col>
            <el-col :span="12">
              <el-button
                class="business resetBtn"
                style="margin-left: 0"
                @click="resetQuery"
                >重置</el-button
              >
            </el-col>
          </el-row>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <!-- 搜索条件 -->
  <!-- 检测项目列表 -->
  <el-form>
    <el-row>
      <p class="pinformation">检测项目列表</p>
      <p class="totalStyle">共 {{ total }} 条数据</p>
      <el-form-item label="指定方法：" style="margin-top: -6px; margin-left: 10px">
        <el-radio-group v-model="jcxmForm.isMethod">
          <el-radio label="0">否</el-radio>
          <el-radio label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-row>
  </el-form>

  <el-table
    id="jcxmTable"
    :data="jcxmList"
    height="60vh"
    class="business"
    ref="jcxmTableRef"
    v-loading="loading"
    :highlight-current-row="highLightRow"
    @row-click="rowClick"
    @select="handleSelectionChange"
    @select-all="handleAllSelectionChange"
    border
  >
    <el-table-column type="selection" width="55" align="center" />
    <el-table-column label="检测类别" align="center" prop="jclbName" width="120" />
    <el-table-column label="检测项目" align="center" prop="jcxmName" width="120">
      <template #default="scope">
        <div :id="scope.row.mJId">
          <span v-html="transformation(scope.row.jcxmName)"></span>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="方法编号" align="center" prop="methodCode" width="140" />
    <el-table-column label="方法名称" align="center" prop="methodName" />
    <el-table-column label="特别选项" align="center" width="150">
      <template #default="scope">
        <el-checkbox-group v-model="scope.row.column1" :min="scope.row.params && scope.row.params.cJId ? 1 : 0" @change="handleSaveColumn1(scope.row)">
          <el-checkbox
            v-for="item in column1List"
            :key="item.value"
            :label="item.value"
            >{{ item.label }}</el-checkbox
          >
        </el-checkbox-group>
      </template>
    </el-table-column>
  </el-table>
  <pagination
    v-show="total > 0"
    :total="total"
    v-model:page="queryParams.pageNum"
    v-model:limit="queryParams.pageSize"
    @pagination="getList"
  />
  <!-- 检测项目列表 -->
</template>
<script setup>
import $ from "jquery";
import {
  listMethodJcxm,
  deleteSelectedJcxm,
  addSelectedJcxm,
  addSelectedJcxmList,
  saveJcxmCypcOrValue
} from "@/api/contract/taskPoint";
const { proxy } = getCurrentInstance();
const highLightRow = ref(true); // 表格选中高亮样式
const loading = ref(false);
const total = ref(0);
const jcxmList = ref([]); // 右侧检测项目列表搜索结果
const column1List = ref([]);
const props = defineProps({
  params: {
    type: Object,
  },
  jclbList: {
    type: Array,
  },
  // 父组件中的方法
  handleSelectionChange: {
    type: Function,
  },
});

const data = reactive({
  jcxmForm: {
    isPackage: 0,
    isMethod: "0",
    isSum: "0",
  },
  queryParams: {
    isLike: "0", // 是否模糊搜索
    pageNum: 1, // 当前页数
    pageSize: 10, // 当前页显示条数
    isMethod: "0",
    jcxmFlag: 0,
  },
});
const { queryParams, jcxmForm } = toRefs(data);

watch(
  () => props.params.isPackage,
  (val) => {
    if (val) {
      jcxmForm.value.isPackage = val;
    }
  }
);

watch(
  () => props.params.packageId,
  (val) => {
    if (val) {
      jcxmForm.value.packageId = val;
      jcxmForm.value.packageName = props.params.packageName;
    } else {
      delete jcxmForm.value.packageId;
      delete jcxmForm.value.packageName;
    }
  }
);

watch(
  () => props.params.isCollect,
  (val) => {
    if (val) {
      jcxmForm.value.isCollect = val;
    }
  }
);
// 对外暴露以下方法或变量
defineExpose({
  setFormParams,
  reselection,
});
function setFormParams(paramsForm) {
  if (!paramsForm.pointId || !paramsForm.pointJclbId) return;
  Object.assign(jcxmForm.value, paramsForm);
  queryParams.value.params = { pointId: paramsForm.pointId };
  queryParams.value.jclbId = paramsForm.pointJclbId;
  handleQuery();
}
// 获取检测项目列表数据
function handleQuery() {
  if (jcxmForm.value.pointId) {
    queryParams.value.pageNum = 1;
    getList();
  } else {
    emit("isAutoSave", true);
  }
  if (queryParams.value.jclbId == "1658880734024134291") {
    //噪声的需要设置特别选项为昼夜间
    column1List.value = [
      { value: "0", label: "昼间" },
      { value: "1", label: "夜间" },
    ];
  } else {
    column1List.value = [];
  }
}

function resetQuery() {
  proxy.resetForm("rightJcxmTable");
  queryParams.value.jclbId = jcxmForm.value.pointJclbId;
  handleQuery();
}

function getList() {
  loading.value = true;
  listMethodJcxm(queryParams.value).then((res) => {
    if (queryParams.value.jclbId == "1658880734024134291") {
      for (let row of res.rows) {
        if (row.column1) {
          row.column1 = row.column1.split("φ");
        }
      }
    }
    jcxmList.value = res.rows;
    total.value = res.total;
    loading.value = false;
    // 是否默认勾选通过id判断
    nextTick(() => {
      jcxmList.value.forEach((row) => {
        if (row.params && row.params.cJId) {
          proxy.$refs["jcxmTableRef"].toggleRowSelection(row);
        }
      });
    });
  });
}
const emit = defineEmits(["setJcxmCount", "pointMove", "isAutoSave"]);
function handleAllSelectionChange(selection) {
  if (jcxmForm.value.isPackage == 1 && !jcxmForm.value.packageId) {
    // proxy.$modal.msgError("分包公司不能为空！");
    // return;
  }
  delete jcxmForm.value.mJId;
  var headerCheckbox = $("#jcxmTable table thead tr label.el-checkbox")[0];
  if (selection.length > 0) {
    // 全选选中
    if (!validateColumn1(selection)) {
      return;
    }
    jcxmForm.value.taskJcxmList = selection;
    const data = JSON.parse(JSON.stringify(jcxmForm.value));
    // delete jcxmForm.value.groupId;
    // delete jcxmForm.value.group_name;
    // delete jcxmForm.value.method_package_id;
    addSelectedJcxmList(data).then((res) => {
      let data = {
        jcxmCount: res.data.jcxmCount,
        jcxmPCount: res.data.jcxmPCount,
      };
      emit("setJcxmCount", data);
      if (jcxmForm.value.isPackage == 0)
        emit("pointMove", headerCheckbox, $("#openSelJcxmDialog"));
      else emit("pointMove", headerCheckbox, $("#openSelJcxmDialog1"));
      getList();
    });
  } else {
    //取消选中
    let cJIds = jcxmList.value.map((item) => item.params.cJId);
    deleteSelectedJcxm(jcxmForm.value.pointId, cJIds).then((res) => {
      let data = {
        jcxmCount: res.data.jcxmCount,
        jcxmPCount: res.data.jcxmPCount,
      };
      emit("setJcxmCount", data);
      getList();
    });
  }
}

function handleSelectionChange(selection, row) {
  if (
    jcxmForm.value.isPackage == 1 &&
    proxy.parseStrEmpty(jcxmForm.value.packageId).length == 0
  ) {
    // proxy.$refs["jcxmTableRef"].toggleRowSelection(row);
    // proxy.$modal.msgError("分包公司不能为空！");
    // return;
  }
  jcxmForm.value.mJId = row.mJId;
  //选中行的主键即任务检测项目的主键，根据此值判断当前操作是选中还是取消选中。
  if (row.params && row.params.cJId) {
    //当前操作是取消选中
    deleteSelectedJcxm(jcxmForm.value.pointId, row.params.cJId)
      .then((res) => {
        delete row.params;
        let data = {
          jcxmCount: res.data.jcxmCount,
          jcxmPCount: res.data.jcxmPCount,
        };
        emit("setJcxmCount", data);
      })
      .catch(() => {
        delete row.params;
      });
  } else {
    //当前操作是选中
    const data = JSON.parse(JSON.stringify(jcxmForm.value));
    // delete data.groupId;
    // delete data.groupName;
    // delete data.methodPackage_id;
    if (row.column1) {
      if (row.column1 instanceof Array) {
        jcxmForm.value.column1 = row.column1.join("φ");
      } else {
        jcxmForm.value.column1 = row.column1;
      }
    }
    if (!validateColumn1(row)) {
      return;
    }
    addSelectedJcxm(jcxmForm.value).then((res) => {
      row.params = { cJId: res.data.cJId };
      let data = {
        jcxmCount: res.data.jcxmCount,
        jcxmPCount: res.data.jcxmPCount,
      };
      emit("setJcxmCount", data);
      let checkboxTd = $("#" + row.mJId)
        .parents("td")
        .prev();
      if (jcxmForm.value.isPackage == 0)
        emit("pointMove", checkboxTd[0], $("#openSelJcxmDialog"));
      else emit("pointMove", checkboxTd[0], $("#openSelJcxmDialog1"));
    });
  }
}
function handleSaveColumn1(row){
if (row.params && row.params.cJId) {
  if(row.column1){
    saveJcxmCypcOrValue({cJId:row.params.cJId,column1:row.column1.join("φ")});
  }
}
}
function validateColumn1(rows) {
  if (rows instanceof Array) {
    let flag = true;
    for (let row of rows) {
      if (queryParams.value.jclbId == "1658880734024134291" && (!rows.column1 || rows.column1.length == 0)) {
        //1658880734024134291:噪声必须指定特别选项
        proxy.$modal.msgError("请指定特别选项！");
        flag = false;
        break;
      }
    }
    if (!flag) {
      return flag;
    }
  } else {
    if (queryParams.value.jclbId == "1658880734024134291" && (!rows.column1 || rows.column1.length == 0)) {
      //1658880734024134291:噪声必须指定特别选项
      proxy.$modal.msgError("请指定特别选项！");
      proxy.$refs["jcxmTableRef"].toggleRowSelection(rows);
      return false;
    }
  }
  return true;
}
function reselection() {
  getList();
}

function rowClick() {
  highLightRow.value = true;
}
function transformation(row) {
  if (row) {
    const a = proxy.getSupAndSub(row);
    return a;
  }
}
</script>
<style>
.el-checkbox-group .el-checkbox {
  margin-right: 10px;
}
</style>
